#!/usr/bin/env python3.6

import datetime
import logging
import os

import telegram
from movie_list import movie_list as movies_list
from sqllite3_db import MovieDB
from telegram import InlineKeyboardButton, InlineKeyboardMarkup
from telegram.ext import Updater, CommandHandler, CallbackQueryHandler

userid = [221941736, ]

token = "707533332:AAFa6lgDc3cKEmkhhC-gfFG6v_1cJctTZAo"
updater = Updater(token=token)
bot = telegram.Bot(token=token)

logging.basicConfig(format='%(asctime)s - %(name)s - %(levelname)s - %(message)s', level=logging.INFO)
logger = logging.getLogger(__name__)


def start(bot, update):
    print(datetime.datetime.now(), update.message.chat_id, update.message.from_user["username"], )
    update.message.reply_text('Hello,我是一只爱小宏的机器人!')


page_num = 1


def movie_list(bot, update):
    print(datetime.datetime.now(), update.message.chat_id, update.message.from_user["username"], )
    global page_num

    page_num = 1
    keyboard = [[InlineKeyboardButton("上一页", callback_data='page-pre'),
                 InlineKeyboardButton("第{}页".format(page_num), callback_data='page-cur'),
                 InlineKeyboardButton("下一页", callback_data='page-next')], ]
    reply_markup = InlineKeyboardMarkup(keyboard)
    moviedb = MovieDB('moviedb.sqlite')
    a = moviedb.browse_data(page_num, 20)
    moviedb.close()
    bot.send_message(chat_id=update.message.chat_id,
                     text=a,
                     parse_mode=telegram.ParseMode.HTML,
                     disable_web_page_preview=True,
                     reply_markup=reply_markup)


# def end(bot, update):
#     keyboard = [[InlineKeyboardButton("Option 1", callback_data='1'),
#                  InlineKeyboardButton("Option 2", callback_data='2')],
#
#                 [InlineKeyboardButton("Option 3", callback_data='3')]]
#
#     reply_markup = InlineKeyboardMarkup(keyboard)
#
#     update.message.reply_text('Please choose:', reply_markup=reply_markup)

def movie_browse(bot, update):
    global page_num
    query = update.callback_query
    if query:
        if format(query.data) == "page-next":
            page_num += 1
        if format(query.data) == "page-cur":
            pass
        elif format(query.data) == "page-pre":
            page_num -= 1

        moviedb = MovieDB('moviedb.sqlite')
        a = moviedb.browse_data(page_num, 20)
        moviedb.close()
        keyboard = [[InlineKeyboardButton("上一页", callback_data='page-pre'),
                     InlineKeyboardButton("第{}页".format(page_num), callback_data='page-cur'),
                     InlineKeyboardButton("下一页", callback_data='page-next')], ]
        reply_markup = InlineKeyboardMarkup(keyboard)

        bot.edit_message_text(chat_id=query.message.chat_id,
                              message_id=query.message.message_id,
                              text=a,
                              disable_web_page_preview=True,
                              parse_mode=telegram.ParseMode.HTML,
                              reply_markup=reply_markup,
                              )


# def myid(bot, update):
#     data = "Your ID = " + str(update.message.chat_id)
#     update.message.reply_text(data)


def movie_download(bot, update):
    if update.message.chat_id in userid:
        id = update.message["text"].split()[1]

        magnetic_link = moviedb.get_magnetic_link(id)
        aria_GID = os.popen("aria2rpc addUri %s --secret youcd --server aria2.youcd.me" % magnetic_link)
        # print("aria_GID",aria_GID.read())
        update.message.reply_text("已经添加 GID:%s" % (aria_GID.read()))
        # update.message.reply_text("已经添加")
    else:
        update.message.reply_text("您没有权限")


def get_magnetic_link(bot, update):
    id = update.message["text"].split()[1]
    moviedb = MovieDB('moviedb.sqlite')
    magnetic_link = moviedb.get_magnetic_link(id)
    moviedb.close()
    update.message.reply_text(magnetic_link)


#
# def test(bot, update):
#     custom_keyboard = [['top-left', 'top-right'], ['bottom-left', 'bottom-right']]
#     reply_markup = telegram.ReplyKeyboardMarkup(custom_keyboard)
#     bot.send_message(chat_id=update.message.chat_id,
#                      text = "Custom Keyboard Test",
#                      reply_markup = reply_markup)
#


def error(bot, update, error):
    logger.warning('Update "%s" caused error "%s"', update, error)


dp = updater.dispatcher
# 注册命令
dp.add_handler(CommandHandler('start', start))
# dp.add_handler(CommandHandler('test', test))


dp.add_handler(CommandHandler('movie_list', movie_list))
dp.add_handler(CallbackQueryHandler(movie_browse))
# dp.add_handler(CallbackQueryHandler(movie_list))
dp.add_handler(CommandHandler('movie_download', movie_download))
dp.add_handler(CommandHandler('getmaglink', get_magnetic_link))

# dp.add_handler(CommandHandler('myid', myid))
# dp.add_handler(CommandHandler('end', end))


# log all errors
dp.add_error_handler(error)

updater.start_polling()
updater.idle()
